package com.das.metrocloud.ssoserver.aop;

import com.das.framework.common.annotation.IgnoreUserToken;
import com.das.framework.common.exception.InvalidRequestException;
import com.das.framework.common.exception.NotAuthorizationException;
import com.das.framework.common.extvo.LoginInfo;


//
import com.das.framework.common.jwt.JWTHelper;


import com.das.framework.common.utils.ContextHandler;   // 线程变量


import com.das.framework.common.utils.Tools;
import com.das.framework.web.spring.utils.WebTools;
import com.das.metrocloud.ssoserver.config.AuthKeyConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


/**
 *  授权拦截器 组件
 *
 */
@Component
public class ServiceAuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Value("${dascloud.authrization.enabled: true}")
    private Boolean authrizationEnabled;


    @Value("${dascloud.authrization.token-header:JwtToken}")
    private String tokenHeader;


    @Value("${dascloud.authrization.auth-key:AuthKey}")
    private String authKeyHeader;


    @Autowired
    private AuthKeyConfig authKeyConfig;


    public ServiceAuthorizationInterceptor() {}


    /**
    *  处理拦截
    **/
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String authorization = WebTools.getRequesetParameterOrHeader(request, this.authKeyHeader);

        String jwtToken = WebTools.getRequesetParameterOrHeader(request, this.tokenHeader);


        if (!(handler instanceof HandlerMethod)) {

            throw new InvalidRequestException("无效的请求 [ " + request.getRequestURL().toString() + " ] ");

        } else if (!this.authrizationEnabled) {

            return super.preHandle(request, response, handler);

        } else {

            //
            HandlerMethod handlerMethod = (HandlerMethod)handler;

            IgnoreUserToken annotation = (IgnoreUserToken)handlerMethod.getBeanType().getAnnotation(IgnoreUserToken.class);

            if (annotation == null) {
                annotation = (IgnoreUserToken)handlerMethod.getMethodAnnotation(IgnoreUserToken.class);
            }

            if (annotation != null) {

                // 不为空就是  需要忽略 认证的 用户请求
                return super.preHandle(request, response, handler);


            } else if (Tools.StringIsNullOrSpace(authorization) && Tools.StringIsNullOrSpace(jwtToken)) {

                throw new NotAuthorizationException("未认证的请求.");

            } else {


                try {
                    // jwtToken + userPubKey   通过JWTHelper 也可解析出信息
                    LoginInfo loginUser = JWTHelper.getInfoFromToken(jwtToken, this.authKeyConfig.getUserPubKey());

                    ContextHandler.setLoginUser(loginUser);  //  存到 线程变量

                    ContextHandler.setJwtToken(jwtToken);    //  存到 线程变量

                    ContextHandler.setAuthKey(authorization);    //  存到 线程变量

                } catch (Exception var9) {
                    throw new NotAuthorizationException("非法的认证请求");
                }


                // 下一个
                return super.preHandle(request, response, handler);
            }
        }
    }
}
